import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';
import * as session from 'express-session';
import * as fs from 'fs';
import * as path from 'path';
import { DataSource } from 'typeorm';

async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    logger: ['error', 'warn', 'log', 'debug', 'verbose'],
  });
  
  // 配置验证管道
  app.useGlobalPipes(
    new ValidationPipe({
      transform: true,
      whitelist: true,
      forbidNonWhitelisted: true,
      skipMissingProperties: false,
      disableErrorMessages: false,
    }),
  );
  
  app.use(
    session({
      secret: 'devops-bi-secret',
      name: 'devops.session',
      rolling: true,
      cookie: { maxAge: 3600000 }, // 1 hour
      resave: false,
      saveUninitialized: true,
    }),
  );
  
  // 允许跨域请求，特别是对埋点API
  app.enableCors({
    origin: true, // 允许所有来源，关键是允许任何网站嵌入埋点脚本
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
    credentials: true,
    allowedHeaders: 'Content-Type,Accept,Authorization',
    exposedHeaders: 'Content-Disposition',
    preflightContinue: false,
    optionsSuccessStatus: 204,
  });
  
  // 执行SQL迁移
  await executeMigrations(app);
  
  const port = process.env.PORT || 3001;
  await app.listen(port);

  console.log(`🚀 DevOps BI Server running on: http://localhost:${port}`);
}

async function executeMigrations(app) {
  try {
    // 获取数据源
    const dataSource = app.get(DataSource);
    
    // 检查并执行SQL迁移脚本
    const migrationsDir = path.join(__dirname, 'migrations');
    
    // 如果目录不存在，则创建
    if (!fs.existsSync(migrationsDir)) {
      return; // 如果目录不存在，直接返回
    }
    
    // 读取所有SQL文件
    const files = fs.readdirSync(migrationsDir)
      .filter(file => file.endsWith('.sql'))
      .sort(); // 按文件名排序，确保按顺序执行
    
    // 逐个执行SQL文件
    for (const file of files) {
      console.log(`执行迁移: ${file}`);
      const sqlContent = fs.readFileSync(path.join(migrationsDir, file), 'utf8');
      
      // 分割多条SQL语句
      const statements = sqlContent.split(';')
        .map(statement => statement.trim())
        .filter(statement => statement);
      
      for (const statement of statements) {
        try {
          await dataSource.query(statement + ';');
        } catch (error) {
          console.warn(`执行SQL语句出错 (可能是表已存在): ${error.message}`);
        }
      }
    }
    
    console.log('所有迁移已执行完成');
  } catch (error) {
    console.error('执行迁移时出错:', error);
  }
}

bootstrap(); 